package com.jiujichaoshi.oauth.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.util.StringUtils;

/**
 * Description: 将认证服务器作为资源服务器发布，如果要调用认证服务器的接口，使用以下方法：
 * 方法一使用浏览器登录后，在浏览器中操作。
 * 方法二，获取access_token，在请求中带上参数access_token，或在请求头中使用bearer认证
 *
 * @author YangLong [410357434@163.com]
 * @version V1.0
 * @date 2021/2/7
 */
@SuppressWarnings("deprecation")
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Value("${spring.application.name:passport}")
    private String resourceId;
    @Autowired
    private DefaultTokenServices tokenService;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(resourceId);
        resources.tokenServices(tokenService);
        super.configure(resources);
    }

    /**
     * 在此处配置认证服务器链接的权限认证
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/user").authenticated()
                .and()
                .requestMatcher((request) -> {
                    String auth = request.getHeader("Authorization");
                    return auth != null &&
                            auth.toLowerCase().contains("bearer") ||
                            !StringUtils.isEmpty(request.getParameter("access_token"));
                }).authorizeRequests().anyRequest().authenticated();
    }
}
